#include "utils.h"
#include <QNetworkInterface>
#include <QUuid>

namespace yc {
namespace baseutils {

QString getDeviceId()
{
    QString id;
    QList<QNetworkInterface> faces = QNetworkInterface::allInterfaces();
    for (const auto& i : faces) {
        if (i.flags().testFlag(QNetworkInterface::IsUp)
            && i.flags().testFlag(QNetworkInterface::IsRunning)
            && !i.flags().testFlag(QNetworkInterface::IsLoopBack)) {
            id = i.hardwareAddress();
            if (!id.isEmpty()) {
                break;
            }
        }
    }
    if (id.isEmpty()) {
        id = QUuid::createUuid().toString().remove('-');
    }
    return id;
}

qint64 strToMS(const QString& time)
{
    if (time.isEmpty()) {
        return -1;
    } else {
        int minutes = 0;
        int secs = 0;
        int msecs = 0;
        QStringList s_list = time.split(':', Qt::SkipEmptyParts);
        if (s_list.size() >= 2) {
            minutes = s_list.at(0).toInt();
            const QString t = s_list.at(1);
            s_list = t.split('.', Qt::SkipEmptyParts);
            if (s_list.size() >= 2) {
                secs = s_list.at(0).toInt();
                const QString ms = s_list.at(1);
                if (ms.length() > 0) {
                    msecs = ms.left(1).toInt();
                }
            } else {
                secs = t.toInt();
            }
        }
        return (minutes * 60 + secs) * 1000 + msecs;
    }
}

QString msToStr(qint64 msecs)
{
    if (msecs >= 0) {
        qint64 secs = msecs / 1000;
        int minute = int(secs / 60);
        QString time = QString("%1:%2.%3")
                               .arg(minute, 2, 10, QChar('0'))
                               .arg(int(secs % 60), 2, 10, QChar('0'))
                               .arg(int(msecs % 1000), 1, 10, QChar('0'));
        return time;
    }
    return QString();
}

// 从url中获得文件名
QString filenameFromUrl(const QString& url)
{
    int i = url.lastIndexOf('/');
    return (i >= 0 ? url.mid(i + 1) : url);
}

// 格式化url
QString formatUrl(const QString& url)
{
    int pos = url.indexOf("//");
    if (pos >= 0) {
        // skip 'http://'
        pos += 2;
        QString valid_url = url.mid(pos);
        return (url.left(pos) + valid_url.replace("//", "/"));
    }
    return url;
}

QString fullUrl(const QString& root, const QString& path)
{
    if (path.startsWith("http://", Qt::CaseInsensitive)
        || path.startsWith("https://", Qt::CaseInsensitive)) {
        return path;
    } else {
        QString full_url = root;
        if (!full_url.isEmpty() && !path.isEmpty() && (full_url.at(full_url.length() - 1) != '/')
            && (path.at(0) != '/')) {
            full_url += '/';
        }
        full_url += path;
        return full_url;
    }
}

QDateTime macroStringToDateTime(const QString& s)
{
    QStringList subs = s.split(' ');
    int count = subs.size();
    if (count >= 4) {
        int day, year;
        QString t;
        if (count == 4) {
            day = subs.at(1).toInt();
            year = subs.at(2).toInt();
            t = subs.at(3);
        } else {
            day = subs.at(2).toInt();
            year = subs.at(3).toInt();
            t = subs.at(4);
        }

        QLocale locale = QLocale::c();
        QList<QString> ms_list;
        for (int i = 1; i <= 12; i++) {
            ms_list.append(locale.monthName(i, QLocale::ShortFormat));
        }

        int mon = ms_list.indexOf(subs.at(0)) + 1;
        QDate d(year, mon, day);
        return QDateTime(d, QTime::fromString(t, "hh:mm:ss"));
    }
    return QDateTime();
}

void enumFiles(const QDir& dir, QList<QString>& files, const QString& exclude_suffixes)
{
    const auto el = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    for (const auto& i : el) {
        if (i.isFile()) {
            if (exclude_suffixes.isEmpty()
                || !exclude_suffixes.contains(i.suffix(), Qt::CaseInsensitive)) {
                files.push_back(i.absoluteFilePath());
            }
        } else if (i.isDir()) {
            enumFiles(QDir(i.absoluteFilePath()), files, exclude_suffixes);
        }
    }
}

bool writeToFile(const QString& file_path, const QByteArray& data)
{
    QFile file(file_path);
    if (file.open(QFile::WriteOnly | QFile::Truncate)) {
        file.write(data);
        file.close();
        return true;
    }
    return false;
}

QByteArray readFromFile(const QString& file_path)
{
    QByteArray data;
    QFile file(file_path);
    if (file.open(QFile::ReadOnly)) {
        data = file.readAll();
        file.close();
    }
    return data;
}

QString& formatJavaScriptString(QString& s)
{
    s.remove("\r\n");
    s.remove("\n");
    s.replace("\\", "\\\\");
    s.replace("'", "\\'");
    return s;
}

} // namespace baseutils
} // namespace yc
